package com.example.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.exam.Exam;
import com.example.domain.exam.ExamQuestion;
import com.example.domain.exam.dto.ExamQueryDTO;
import com.example.domain.exam.dto.ExamRankDTO;
import com.example.domain.exam.vo.ExamRankVO;
import com.example.domain.exam.vo.ExamVO;
import com.example.domain.user.UserExam;
import com.example.mapper.exam.ExamMapper;
import com.example.mapper.exam.ExamQuestionMapper;
import com.example.mapper.user.UserExamMapper;
import com.example.redis.service.RedisService;
import com.example.security.exception.ServiceImplException;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.CacheConstants;
import oj.common.core.enums.ExamListType;
import oj.common.core.enums.ResultCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ExamCacheManager {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamQuestionMapper examQuestionMapper;
    public Long getExamRankListSize(Long examId) {
        String examRankKey = getExamRankListKey(examId);
        return redisService.getListSize(examRankKey);
    }

    public Long getQuestionExamListSize(Long examId) {
        String questionExamListKey = getQuestionExamListKey(examId);
        return redisService.getListSize(questionExamListKey);
    }

    public Long getListSize(Integer examListType,Long userId) {
        String examListKey = getExamListKey(examListType,userId);
        return redisService.getListSize(examListKey);
    }

    /**
     * 这个方法是将后端竞赛列表带上已报名的信息
     * @param userId
     * @return
     */
    public List<Long> getAllExamList(Long userId) {
        String examListKey = getExamListKey(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, 0, -1, Long.class);
        if (CollectionUtil.isNotEmpty(examIdList)) {
            return examIdList;
        }
        //此时从数据库中查询相应的数据
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId));
        //此时需要将数据转换成相应的数据
        if(CollectionUtil.isEmpty(userExamList)) {
            return null;
        }
        //此时还需要进行刷新缓存。
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
        return userExamList.stream().map(UserExam::getExamId).collect(Collectors.toList());
    }
    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO,Long userId) {
        //需要从redis中拿数据的时候，需要进行分页查询
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);
        log.info("examKey"+examListKey);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            //这里可能有问题，在针对个人竞赛的时候，但是产生了未报名的行为的
            //todo
            //因为现在没有出现问题是因为现在缓存中存在数据，所以才导致不会出现问题
            examVOList = getExamVOListByDB(examQueryDTO,userId); //从数据库中获取数据
            refreshCache(examQueryDTO.getType(),userId);
        }
        return examVOList;
    }

    private List<ExamVO> getExamVOListByDB(ExamQueryDTO examQueryDTO,Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if(ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())) {
            //查询用户的竞赛
            return userExamMapper.selectUserExamList(userId);
        } else {
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    public void addUserExamCache(Long userId,Long examId) {
        String userExamListKey = getExamListKey(ExamListType.USER_EXAM_LIST.getValue(),userId);
        redisService.leftPushForList(userExamListKey, examId);
    }
    //刷新缓存逻辑
    public void refreshCache(Integer examListType,Long userId) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, 1)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, 1)
                    .orderByDesc(Exam::getCreateTime));
        }else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            BeanUtils.copyProperties(examVOList, examList);
            //这是c端用户个人竞赛刷新缓存的方法
        }
        //我的竞赛分页查询
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType,userId));
        redisService.rightPushAll(getExamListKey(examListType,userId), examIdList);      //刷新列表缓存
    }
    public void refreshExamQuestionCache(Long examId) {
        //查找表
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if(CollectionUtil.isEmpty(examQuestionList)) {
            return;
        }
        List<Long> longList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        redisService.rightPushAll(getQuestionExamListKey(examId),longList);
        //避免浪费时间，但是这里的话要注意进行刷新缓存，
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getQuestionExamListKey(examId),seconds);
    }
    public Object preQuestion(Long examId,Long questionId) {
        String examQuestionKey = getQuestionExamListKey(examId);
        Long index = redisService.indexOfForList(examQuestionKey,questionId);
        if(index == 0) {
            throw new ServiceImplException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(examQuestionKey,index-1,Long.class);
    }

    public Object nextQuestion(Long examId,Long questionId) {
        String examQuestionKey = getQuestionExamListKey(examId);
        Long index = redisService.indexOfForList(examQuestionKey,questionId);
        if(index == getQuestionExamListSize(examId)-1) {
            throw new ServiceImplException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(examQuestionKey,index+1,Long.class);
    }
    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getQuestionExamListKey(examId), 0, Long.class);
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    private String getExamListKey(Integer examListType,Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else if(ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            return CacheConstants.USER_EXAM_LIST+userId;
        } else {
           return "";
        }
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }
    public String getQuestionExamListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST+examId;
    }
    private String getExamRankListKey(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }

    public void refreshExamRankCache(ExamRankDTO examRankDTO) {

        List<ExamRankVO> examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
        if(CollectionUtil.isEmpty(examRankVOList)) {
            return ;
        }
        redisService.rightPushAll(getExamRankListKey(examRankDTO.getExamId()),examRankVOList);
    }

    public List<ExamRankVO> getExamRankList(ExamRankDTO examRankDTO) {
        String examRankListKey = getExamRankListKey(examRankDTO.getExamId());
        int start = (examRankDTO.getPageNum()-1)*examRankDTO.getPageSize();
        int end = examRankDTO.getPageNum()*examRankDTO.getPageSize()-1;
        return redisService.getCacheListByRange(examRankListKey,start,end,ExamRankVO.class);
    }
}